package org.example.file;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.StringBufferInputStream;

public class FileTest {

    //写入一行字符到文件
    public static void main(String[] args) throws Exception {

        fileReadWriteUsingChar();

    }

    public static void readStringToFile() {
        //1.构造输入流
        try (BufferedInputStream bif = new BufferedInputStream(new StringBufferInputStream("abc"));
             FileOutputStream fos = new FileOutputStream(new File("C:/test/1.txt"))) {
            byte[] buf = new byte[4];
            //2.构造输出流
            int readInt = 0;
            while ((readInt = bif.read(buf)) != -1) {
                fos.write(buf, 0, readInt);
            }
            System.out.println("写出完毕");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取A文件的内容写到B文件，使用字符流
     */
    public static void fileReadWriteUsingChar() throws Exception {
        //读取文件的输入字符流
        FileReader fileReader = new FileReader("C:/test/1.txt");
        //写出到文件的输出字符流
        FileWriter fileWriter = new FileWriter("C:/out/1.txt");
        char[] bufChar = new char[12];
        //标记读取了多少个字符
        int charRead = 0;
        while ((charRead = fileReader.read(bufChar)) != -1) {
            fileWriter.write(bufChar, 0, charRead);
        }
        fileWriter.flush();
        System.out.println("写出文件结束");

    }
}
